package example.demo.route.handler.impl;

import example.demo.route.handler.SqlHandlerParent;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.jdbc.ConnectionLogger;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Invocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Component
@Order(0)
public class InsertSqlHandler extends SqlHandlerParent /*implements InitializingBean*/ {
//    @Value("${rao.table-sum}")
//    private int tableSum;

    //INSERT INTO t_user ( email ) VALUES ( ? )
    @Override
    public String getTableName(String sql) {
        //获取的table-name已经没有了前后空格
        return sql.substring(sql.indexOf("INTO") + 5, sql.indexOf("(") - 1);
    }


//    public static void main(String[] args) {//wwt_userww 说明前后两个空格
//        InsertSqlHandler selectSqlHandler = new InsertSqlHandler();
//        System.out.println(selectSqlHandler.getTableName("INSERT INTO t_user ( email ) VALUES ( ?").
//                replaceAll(" ", "ww"));
//    }

    @Override
    public boolean isSupport(String sql) {
        return sql.contains("INSERT") || sql.contains("insert");
    }

    @Override
    public Object handler(Integer[] integers, String sql, Invocation invocation, BoundSql boundSql, Field sqlField, StatementHandler statementHandler) throws Exception {
        Object parameterObject = boundSql.getParameterObject();

        /*没查到，返回一个空的list，省的后面包空指针异常*/
//        return new ArrayList<>();
        return invocation.proceed();
    }


}
